<?php

class myUser extends sfGuardSecurityUser
{
    public function apiAuth($user, $token = true, $con = null)
    {
        $this->signIn($user);

        // save last login
        $user->setLastLogin(date('Y-m-d H:i:s'));
        $user->save($con);

        // create new token?
        if ($token)
        {
            $expiration_age = sfConfig::get('app_api_token_expiration_age', 15 * 24 * 3600);

            // remove old tokens
            Doctrine_Core::getTable('UserToken')->createQuery()
                ->delete()
                ->where('created_at < ?', date('Y-m-d H:i:s', time() - $expiration_age))
                ->execute();

            // remove other token from this user
            Doctrine_Core::getTable('UserToken')->createQuery()
                ->delete()
                ->where('user_id = ?', $user->getId())
                ->execute();

            // generate new tokens
            $key = $this->generateRandomToken();

            // save key
            $ut = new UserToken();
            $ut->setToken($key);
            $ut->setUser($user);
            $ut->save($con);

            // return token
            return $key;
        }
    }

    /**
     * Signs in the user on the application.
     *
     * @param sfGuardUser $user The sfGuardUser id
     * @param boolean $remember Whether or not to remember the user
     * @param Doctrine_Connection $con A Doctrine_Connection object
     */
    public function signIn($user, $remember = false, $con = null)
    {
        // signin
        $this->setAttribute('user_id', $user->getId(), 'sfGuardSecurityUser');
        $this->setAuthenticated(true);
        $this->clearCredentials();
        $this->addCredentials($user->getAllPermissionNames());
    }

    /**
     * Returns a random generated token.
     *
     * @param int $len The token length
     * @return string
     */
    protected function generateRandomToken($len = 20)
    {
        return base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
    }

    public function getName()
    {
        if($this->getGuardUser()->getFirstName()){
            return ($this->getGuardUser()->getLastName() ? mb_substr($this->getGuardUser()->getLastName(),0,1).'.' : '') . $this->getGuardUser()->getFirstName();
        }
        else
            return $this->getGuardUser()->getUsername();
    }
}
